<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>TEST OL Albers v2</title>
	<script src="ol.js"></script>
	<script src="proj4.js"></script>
	<script src="reproject.js"></script>
	<link rel="stylesheet" href="ol.css" />
</head>

<body>
	<!-- Row 1-->

	<!-- ROW 2 -->
	<div style="clear:both;">
		<!-- Col 1 -->
		<div style="width: 100%;">
			<div id="map" style="width:100%;height:660px;border:1px solid black;"></div>
		</div>
	</div>
	<script>

		var map = null ;

		//---------- OpenLayer -------------------------------
		const projection = ol.proj.get('EPSG:4326');
		const projectionExtent = projection.getExtent();
		const size = ol.extent.getWidth(projectionExtent) / 256;
		const resolutions = new Array(19);
		const matrixIds = new Array(19);
		for (let z = 0; z < 19; ++z) {
			// generate resolutions and matrixIds arrays for this WMTS
			resolutions[z] = size / Math.pow(2, z);
			matrixIds[z] = z;
		}

		//背景边界
		const bgstyle = function () {
			return new ol.style.Style({
				stroke: new ol.style.Stroke({
					color: '#BA0000',
					width: 1,
				}),
			});
		}


		//定义中国Albers投影 这里使用的是proj4.js
		proj4.defs("USER:100001","+proj=aea +lat_0=-15 +lon_0=105 +lat_1=25 +lat_2=47 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +type=crs");
		//QGIS 定义中国区albers有问题，只好使用自带proj.db的亚洲区albers做测试ESRI:102025，由于102025经纬度跨越180度线，qgis有个bug不能计算其范围
		//我直接修改了proj.db 102025 的extent为中国区，勉强实现代码投影变换的功能逻辑，后面找时间再尝试如何把中国albers写入proj.db。
		proj4.defs("ESRI:102025","+proj=aea +lat_0=30 +lon_0=95 +lat_1=15 +lat_2=65 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +type=crs");
		ol.proj.proj4.register(proj4); // ol
		let projectionAlbers = ol.proj.get("USER:100001");// ol
		let projection102025 = ol.proj.get("ESRI:102025");// ol


		// ol 没办法自动将geojson转换为albers坐标，这里只能使用proj4逐个坐标转换了。
		// 然后将转完的geojson对象构建一个图层插入到openlayer里面。
		const geojsonUrl = "http://localhost:8080/countries.geojson" ;
		var reprojGeojson = null;
		fetch(geojsonUrl)
		.then(response => response.json())
		.then(data => {
			//console.log( data ) ;// 这个data是4326坐标的geojson对象。
			reprojGeojson = reproject(data,"EPSG:4326", "USER:100001" , proj4 ) ;
			//console.log( data2 ) ;// data2 是坐标转换成alber的geojson对象。
			let source2 =  new ol.source.Vector({ 
				features: new ol.format.GeoJSON().readFeatures(reprojGeojson), 
			});
			let geojson4326Layer2 = new ol.layer.Vector({ 
				source: source2, style: bgstyle 
			});
			console.log("add layer");
			map.addLayer(geojson4326Layer2) ;
		})


		//3857 XYZ Layer
		let xyz3857Layer = null ;
		{
			//https://api.maptiler.com/maps/basic-v2/256/{z}/{x}/{y}.png?key=4SbPVVkPORGgXetw2vsf
			xyz3857Layer = new ol.layer.Tile(
					{
						source: new ol.source.XYZ(
							{
								projection:"EPSG:3857",
								url:"https://api.maptiler.com/maps/basic-v2/256/{z}/{x}/{y}.png?key=4SbPVVkPORGgXetw2vsf"
							}
						)
					}
				);

		}

		//本身是albers的WMS图层 坐标稍微有点不一样
		//http://localhost:8080/cgi-bin/qgis_mapserv.fcgi.exe?SERVICE=WMTS&REQUEST=GetCapabilities&MAP=E:/data/test-21.qgs
		let albersWmsLayer = null ;
		{ 
			// albersWmsLayer = new ol.layer.WebGLTile({
			// 	source: new ol.source.TileWMS({
			// 	  url: 'http://192.168.56.107/qgisserver?MAP=/home/hadoop/test-albers.qgs',
			// 	  params: {'LAYERS': 'china-from-duan', 'TILED': true},
			// 	  serverType: 'qgis',
			// 	  transition: 0,
			// 	}),
			// })

			const size = 4021243.707*2.0 / 256;
			const resolutions = new Array(8);
			const matrixIds = new Array(8);
			for (let z = 0; z < 8; ++z) {
			// generate resolutions and matrixIds arrays for this WMTS
				resolutions[z] = size / Math.pow(2, z);
				matrixIds[z] = z;
			}


			// albersWmsLayer = new ol.layer.Tile({
			// 	opacity: 0.7,
			// 	source: new ol.source.WMTS({
			// 		attributions:'wmts',
			// 		url: 'http://localhost:8080/cgi-bin/qgis_mapserv.fcgi.exe?SERVICE=WMTS&REQUEST=GetCapabilities&MAP=E:/data/test-22ok.qgs',
			// 		layer: 'china-from-duan',
			// 		matrixSet: 'ESRI:102025',
			// 		format: 'image/png',
			// 		projection: projection102025,
			// 		tileGrid: new ol.tilegrid.WMTS({
			// 			origin: [-4021243.707, 3344967.112],
			// 			resolutions: resolutions,
			// 			matrixIds: matrixIds,
			// 		}),
			// 		style: 'default',
			// 		wrapX: true,
			// 	}),
			// });
 
			const url1='http://localhost:8080/cgi-bin/qgis_mapserv.fcgi.exe?SERVICE=WMTS&REQUEST=GetCapabilities&MAP=E:/data/test-22ok.qgs';
			const parser = new ol.format.WMTSCapabilities();
			fetch(url1)
			  .then(function (response) {
			    return response.text();
			  })
			  .then(function (text) {
			    const result = parser.read(text);
			    const options = ol.source.WMTS.optionsFromCapabilities(result, {
			      layer: 'china-from-duan',
			      matrixSet: 'ESRI:102025',
			    });
				albersWmsLayer = new ol.layer.Tile({
					opacity: 0.7,
					source: new ol.source.WMTS(options),
				});
				console.log("add layer wmts");
				console.log(JSON.stringify(options));
				map.addLayer(albersWmsLayer) ;
			}) ;

		}


		//初始化OpenLayer
		map = new ol.Map({
			target: 'map',
			layers: [
				xyz3857Layer
				//,albersWmsLayer
			],
			view: new ol.View({
				//projection: projectionAlbers, //  GeoJson4326 BAD 好像栅格瓦片是可以换算自定义坐标的，矢量不行？
				projection: "USER:100001", //  GeoJson4326 BAD 矢量不行？
				//projection: "EPSG:4326", //  GeoJson4326 OK  但是矢量epsg的就行
				//projection: "EPSG:3857", //  GeoJson4326 OK  但是矢量epsg的就行 
				// extent:[-3000000, 1000000 , 3000000, 7350000],
				center: [0, 0],
				zoom: 2,
			}),
		});

	</script>



</body>

</html>